package gui;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

@SuppressWarnings("serial")
public class GuiCredits extends JPanel {
	
	private final boolean DEBUG = false;
	
	private String version;
	private String homepageAddress = "http://web.it.kth.se/~cmasus/";
	
	public GuiCredits(String version) {
		
		this.version = version;
		
		setLayout(new GridBagLayout());
		GridBagConstraints gbc = new GridBagConstraints();
		
		URL imgURL = ClassLoader.getSystemResource("skin/SyncITLogo.gif");
		ImageIcon logo = new ImageIcon(imgURL);
		JButton iconButton = new JButton(logo);
		iconButton.setToolTipText("Go to the Sync IT homepage");
		iconButton.addActionListener(new IconButtonListener());
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weighty = 1.0; //request any extra vertical space
		gbc.anchor = GridBagConstraints.FIRST_LINE_START; //top left of space
		gbc.insets = new Insets(23, 55, 0, 0); //padding
		gbc.gridx = 2; //third column
		gbc.gridy = 0; //first row
		add(iconButton, gbc);
		
		JLink openManualLabel = new JLink("Open Manual");
		openManualLabel.setFont(new Font("Arial", Font.PLAIN, 12));
		openManualLabel.setToolTipText("This will open the Sync IT manual");
		openManualLabel.addMouseListener(new CreditsMouseListener());
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weighty = 1.0; //request any extra vertical space
		gbc.anchor = GridBagConstraints.LAST_LINE_START; //bottom left of space
		gbc.insets = new Insets(0, 118, 15, 0); //padding
		gbc.gridx = 1; //second column
		gbc.gridy = 2; //third row
		add(openManualLabel, gbc);
	}
	
	private void openBrowser(String url) {
		
		URL pdfURL = null;
		try {
			pdfURL = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		
		String os = System.getProperty("os.name").toUpperCase();
		if(DEBUG) System.out.println("OS is: " + os);
		
		Runtime rt = Runtime.getRuntime();
		try {
			// Windows
			if (os.indexOf("WIN") >= 0) {
				String[] cmd = new String[4];
				cmd[0] = "cmd.exe";
				cmd[1] = "/C";
				cmd[2] = "start";
				cmd[3] = "" + pdfURL;
				rt.exec(cmd);
			}
			// Mac
			else if (os.indexOf("MAC") >= 0) {
				rt.exec("open " + pdfURL);
			}
			// Linux and others
			else {
				//prioritized 'guess' of users' preference
				String[] browsers = {"firefox", "mozilla", "opera", "netscape", "epiphany", "konqueror", "links", "lynx"};
				
				StringBuffer cmd = new StringBuffer();
				for (int i=0; i<browsers.length; i++) {
					cmd.append( (i==0  ? "" : " || " ) + browsers[i] +" \"" + pdfURL + "\" ");
				}

				rt.exec(new String[] { "sh", "-c", cmd.toString() });
			}
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private class CreditsMouseListener extends MouseAdapter {
		
		public void mouseClicked(MouseEvent event) {
			
			setCursor(Cursor.getDefaultCursor());
			if( Desktop.isDesktopSupported() ) {
				File manualFile = new File( (new File("").getAbsoluteFile()) + File.separator + "manual.pdf");
				if(manualFile.exists()) {
					try {
						Desktop.getDesktop().open(manualFile);
					} catch (IOException e) {
						JOptionPane.showMessageDialog(null, "Can't find a program to open pdf-files\n" +
								"Go to " + homepageAddress + "manual.pdf" + " to download the manual",
								" Error opening manual",
								JOptionPane.INFORMATION_MESSAGE);
					}
				}
				else {
					if(DEBUG) System.out.println("The manual does not exist in the local folder.");
					try {
						Desktop.getDesktop().browse( URI.create(homepageAddress + "manual.pdf") );
					} catch (IOException e) {
						JOptionPane.showMessageDialog(null, "Can't find the default web browser\n" +
								"Go to " + homepageAddress + "manual.pdf" + " to download the manual",
								" Error opening manual",
								JOptionPane.INFORMATION_MESSAGE);
					}
				}
			}
			else {
				openBrowser(homepageAddress + "manual.pdf");
			}
		}

		public void mouseEntered(MouseEvent event) {
			
			setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		}

		public void mouseExited(MouseEvent event) {
			
			setCursor(Cursor.getDefaultCursor());
		}
	}
	
	private class IconButtonListener implements ActionListener {
		
		public void actionPerformed(ActionEvent event) {
			if( Desktop.isDesktopSupported() ) {
				try {
					Desktop.getDesktop().browse( URI.create(homepageAddress) );
				} catch (IOException e) {
					JOptionPane.showMessageDialog(null, "Can't find the default web browser\n" +
							"to open the homepage " + homepageAddress,
							" Error opening manual",
							JOptionPane.INFORMATION_MESSAGE);
				}
			}
			else {
				openBrowser(homepageAddress);
			}
		}
		
	}
	
	public void paintComponent(Graphics page) {
		
		super.paintComponent(page);
		
		page.drawString("Version " + version, 250, 14); // 255, 14 is better in windows //TODO set global font and size
		
		page.setFont(new Font("Arial", Font.BOLD + Font.ITALIC, 14));
		page.drawString("Programmers:", 40, 45);
		page.drawString("Christian Masus", 60, 75);
		page.drawString("cmasus@kth.se", 60, 90);
		page.drawString("Fidel Lopez", 60, 120);
		page.drawString("fidella@kth.se", 60, 135);
		page.drawString("Jim Jansson", 60, 165);
		page.drawString("jimj@kth.se", 60, 180);
		page.drawString("Mikael Gr�nmark", 60, 210);
		page.drawString("gronmark@kth.se", 60, 225);
		page.drawString("Niklas Andersson", 60, 255);
		page.drawString("nanders@kth.se", 60, 270);
	}
}

// Class to make a JLabel look more like an Internet link
@SuppressWarnings("serial")
class JLink extends JLabel {
	JLink(String text) {
		setForeground(Color.blue);
		setText(text);
	}
	
	public void paintComponent(Graphics page) {
		super.paintComponent(page);
		Dimension jLinkDim = this.getPreferredSize();
		page.setColor(Color.blue);
		page.drawLine(0, jLinkDim.height-2, jLinkDim.width-1, jLinkDim.height-2);
	}
}

